/**
 * 简易tab, 灯笼tab方法，属性基类
 */
import { EMIT_PARAMS_OBJ } from '@/utils/constant';
import { nextTick } from 'vue';

export default {
  data() {
    return {
      carouselTimer: null, // 轮播定时器
      initActiveTimer: null,
    };
  },
  methods: {
    clickTab(index) {
      if (!this.isClickable(this.tabData[index])) {
        return;
      }

      for (let i = 0; i < this.tabData.length; i++) {
        if (i === index) {
          this.tabData[i].isActived = true;

          // 事件发出
          const item = {
            ...this.tabData[i],
            tabIndex: index,
          };
          this.sendAllMessages(item, index);
        } else {
          this.tabData[i].isActived = false;
        }
      }
      this.runCarousel();
    },
    sendAllMessages(item) {
      try {
        this.executeAction('', item);
        const evtKey = this.orgConfig.events[0].key || 'item-click';
        const outObj = {};
        const { key } = this.config.events[0].parameters[0];

        outObj[key] = item.label;
        outObj[EMIT_PARAMS_OBJ] = {
          eventKey: this.config.events[0].key,
          keys: [key],
          widgetInstanceId: this.widgetInstanceId,
          parameters: { [key]: item.label },
          type: 'terms',
          sendTime: new Date().getTime(),
        };
        this.clickedData = item;
        this.vsEmit(evtKey, outObj);
      } catch (err) {}
    },
    initActivedTabClick() {
      if (this.activeIndex !== -1) {
        nextTick(() => {
          if (this.initActiveTimer) {
            clearTimeout(this.initActiveTimer);
          }
          this.initActiveTimer = setTimeout(() => {
            this.clickTab(this.activeIndex);
          }, 700);
        });
      }
    },
    runCarousel() {
      // 幻灯片轮播
      clearTimeout(this.carouselTimer);
      const { property } = this.config.config;
      if (property.isCarouselOn) {
        const { tabData } = this;
        const curTab = tabData.find(n => n.isActived === true);
        const curIndex = tabData.indexOf(curTab);
        let nextTab = tabData.find(n => {
          // 查后面一个
          const nIndex = tabData.indexOf(n);
          return nIndex > curIndex && this.isClickable(n) && n.isCarousel;
        });
        if (!nextTab) {
          // 查第一个
          nextTab = tabData.find(n => this.isClickable(n) && n.isCarousel);
        }

        if (nextTab) {
          const nextIndex = tabData.indexOf(nextTab);
          this.carouselTimer = setTimeout(() => {
            this.clickTab(nextIndex);
            this.runCarousel();
          }, this.carouselTime * 1000);
        }
      }
    },

    isClickable(tabItem) {
      if (this.$options.name === 'SimpleTabContainer') {
        return true;
      }
      if (tabItem.isClickable) {
        return true;
      }
      return false;
    },
  },

  beforeUnmount() {
    this.saveCompHistory(['tabData', 'configData']);
    if (this.initActiveTimer) {
      clearTimeout(this.initActiveTimer);
    }
  },
};
